import http from '@/utils/http';
import type { ApiPaginatedResponse, ApiResponse } from '@/types';

// 产品相关类型定义
export interface Product {
  id: number;
  name: string;
  slug?: string;
  category_id?: number;
  brand: string;
  model?: string;
  sku?: string;
  price: string | number; // 后端返回字符串格式
  original_price?: string | number; // 后端返回字符串格式
  stock: number;
  sales: number;
  rating: string | number; // 后端返回字符串格式
  review_count: number;
  short_description?: string;
  description?: string;
  specifications?: any;
  features?: any;
  images?: any;
  tags?: any;
  status: string;
  category: string;
  isFeatured: boolean;
  isHot: boolean;
  meta_title?: string;
  meta_description?: string;
  weight?: number;
  dimensions?: any;
  warranty?: string;
  created_at: string;
  updated_at: string;
}

export interface ProductConfig {
  id: number;
  name: string;
  description: string;
  total_price: string | number; // 后端可能返回字符串格式
  image_url?: string;
  category: string;
  components: any;
  performance_score: string | number; // 后端可能返回字符串格式
  created_at: string;
  updated_at: string;
}

export interface ProductQueryParams {
  page?: number;
  limit?: number;
  keyword?: string;
  category?: string;
  category_id?: number;
  status?: string;
  brand?: string;
  minPrice?: number;
  maxPrice?: number;
  startDate?: string;
  endDate?: string;
  isFeatured?: boolean;
  isHot?: boolean;
}

export interface ConfigQueryParams {
  page?: number;
  limit?: number;
  keyword?: string;
  category?: string;
  minPrice?: number;
  maxPrice?: number;
}

export interface CreateProductRequest {
  name: string;
  slug?: string;
  category_id?: number;
  brand: string;
  model?: string;
  sku?: string;
  price: number; // 创建时发送数字格式
  original_price?: number; // 创建时发送数字格式
  stock?: number;
  sales?: number;
  rating?: number; // 创建时发送数字格式
  review_count?: number;
  short_description?: string;
  description?: string;
  specifications?: any;
  features?: any;
  images?: any;
  tags?: any;
  status?: string;
  category?: string;
  isFeatured?: boolean;
  isHot?: boolean;
  meta_title?: string;
  meta_description?: string;
  weight?: number;
  dimensions?: any;
  warranty?: string;
}

export interface UpdateProductRequest extends Partial<CreateProductRequest> {}

export interface CreateConfigRequest {
  name: string;
  description: string;
  total_price: number; // 创建时发送数字格式
  image_url?: string;
  category: string;
  components: any;
  performance_score?: number; // 创建时发送数字格式
}

export interface UpdateStockRequest {
  stock: number;
  operation?: 'set' | 'add' | 'subtract';
}

export interface BatchUpdateStatusRequest {
  ids: number[];
  status: string;
}

export interface BatchUpdateFlagsRequest {
  ids: number[];
  isFeatured?: boolean;
  isHot?: boolean;
}

// 产品配置相关接口
export interface ProductConfigData {
  product_id: number;
  config_data: Record<string, any>;
  config_name?: string;
  config_description?: string;
}

export interface UpdateProductConfigRequest {
  config_data: Record<string, any>;
  config_name?: string;
  config_description?: string;
}

export interface ProductStatistics {
  products: {
    total_products: number;
    active_products: number;
    inactive_products: number;
    discontinued_products: number;
    out_of_stock: number;
    low_stock: number;
    featured_products: number;
    hot_products: number;
    avg_price: string | number; // 后端可能返回字符串格式
    total_stock: number;
    avg_rating: string | number; // 后端可能返回字符串格式
    total_sales: number;
  };
  configs: {
    total_configs: number;
    avg_config_price: string | number; // 后端可能返回字符串格式
    avg_performance_score: string | number; // 后端可能返回字符串格式
  };
  categories: Array<{
    category: string;
    product_count: number;
    avg_price: string | number; // 后端可能返回字符串格式
    total_sales: number;
  }>;
  brands: Array<{
    brand: string;
    product_count: number;
    avg_price: string | number; // 后端可能返回字符串格式
    total_sales: number;
  }>;
  priceRanges: Array<{
    price_range: string;
    product_count: number;
  }>;
}

export interface BrandItem {
  brand: string;
  product_count: number;
}

export interface CategoryItem {
  category: string;
  product_count: number;
}

/**
 * 获取产品列表（支持搜索和分页）
 */
export const getProductList = async (params: ProductQueryParams): Promise<ApiPaginatedResponse<Product>> => {
  const response = await http.get('/admin/products', { params });
  return response.data;
};

/**
 * 转换后端产品数据为前端配置数据格式
 */
const transformProductToConfig = (product: Product): ProductConfig => {
  return {
    id: product.id,
    name: product.name,
    description: product.description || product.short_description || '',
    total_price: product.price, // 将 price 映射为 total_price
    image_url: product.images ? (typeof product.images === 'string' ? product.images : (product.images as any)?.main || '') : '',
    category: product.category,
    components: product.specifications || {}, // 将 specifications 映射为 components
    performance_score: (product as any).performance_score || product.rating || 0, // 使用 rating 作为性能评分的备选
    created_at: product.created_at,
    updated_at: product.updated_at,
  };
};

/**
 * 转换前端配置数据为后端产品数据格式
 */
const transformConfigToProduct = (config: CreateConfigRequest): CreateProductRequest => {
  return {
    name: config.name,
    brand: 'Custom Config', // 默认品牌
    price: config.total_price, // 将 total_price 映射为 price
    description: config.description,
    short_description: config.description.substring(0, 100), // 截取前100字符作为简短描述
    specifications: config.components, // 将 components 映射为 specifications
    category: config.category,
    rating: config.performance_score || 0, // 将性能评分存储在 rating 字段
    images: config.image_url ? { main: config.image_url } : undefined,
    status: 'active',
    stock: 1, // 配置默认库存为1
  };
};

/**
 * 获取配置列表（支持搜索和分页）
 */
export const getConfigList = async (params: ConfigQueryParams): Promise<ApiPaginatedResponse<ProductConfig>> => {
  const response = await http.get('/admin/products/configs', { params });
  
  // 转换数据格式
  if (response.data.success && response.data.data.items) {
    const transformedItems = response.data.data.items.map(transformProductToConfig);
    return {
      ...response.data,
      data: {
        ...response.data.data,
        items: transformedItems
      }
    };
  }
  
  return response.data;
};

/**
 * 获取产品详情
 */
export const getProductDetail = async (id: number): Promise<Product> => {
  const response = await http.get(`/admin/products/${id}`);
  return response.data.data;
};

/**
 * 创建产品
 */
export const createProduct = async (data: CreateProductRequest): Promise<Product> => {
  const response = await http.post('/admin/products', data);
  return response.data.data;
};

/**
 * 创建配置
 */
export const createConfig = async (data: CreateConfigRequest): Promise<ProductConfig> => {
  // 转换数据格式
  const transformedData = transformConfigToProduct(data);
  const response = await http.post('/admin/products/configs', transformedData);
  
  // 转换返回数据格式
  if (response.data.success && response.data.data) {
    return transformProductToConfig(response.data.data);
  }
  
  return response.data.data;
};

/**
 * 更新产品信息
 */
export const updateProduct = async (id: number, data: UpdateProductRequest): Promise<Product> => {
  const response = await http.put(`/admin/products/${id}`, data);
  return response.data.data;
};

/**
 * 更新库存
 */
export const updateStock = async (id: number, data: UpdateStockRequest): Promise<{
  id: number;
  oldStock: number;
  newStock: number;
  operation: string;
}> => {
  const response = await http.post(`/admin/products/${id}/update-stock`, data);
  return response.data.data;
};

/**
 * 批量更新产品状态
 */
export const batchUpdateStatus = async (data: BatchUpdateStatusRequest): Promise<{
  updatedCount: number;
  status: string;
}> => {
  const response = await http.post('/admin/products/batch-update-status', data);
  return response.data.data;
};

/**
 * 批量更新特色/热门标记
 */
export const batchUpdateFlags = async (data: BatchUpdateFlagsRequest): Promise<{
  updatedCount: number;
  isFeatured?: boolean;
  isHot?: boolean;
}> => {
  const response = await http.post('/admin/products/batch-update-flags', data);
  return response.data.data;
};

/**
 * 删除产品
 */
export const deleteProduct = async (id: number): Promise<void> => {
  await http.delete(`/admin/products/${id}`);
};

/**
 * 获取产品统计信息
 */
export const getProductStatistics = async (): Promise<ProductStatistics> => {
  const response = await http.get('/admin/products/statistics/overview');
  return response.data.data;
};

/**
 * 获取品牌列表
 */
export const getBrandList = async (): Promise<BrandItem[]> => {
  const response = await http.get('/admin/products/brands/list');
  return response.data.data;
};

/**
 * 获取类别列表
 */
export const getCategoryList = async (): Promise<CategoryItem[]> => {
  const response = await http.get('/admin/products/categories/list');
  return response.data.data;
}; 

/**
 * 更新配置
 */
export const updateConfig = async (id: number, data: Partial<CreateConfigRequest>): Promise<ProductConfig> => {
  // 转换数据格式
  const transformedData = transformConfigToProduct(data as CreateConfigRequest);
  const response = await http.put(`/admin/products/${id}`, transformedData);
  
  // 转换返回数据格式
  if (response.data.success && response.data.data) {
    return transformProductToConfig(response.data.data);
  }
  
  return response.data.data;
};

/**
 * 删除配置
 */
export const deleteConfig = async (id: number): Promise<void> => {
  await http.delete(`/admin/products/${id}`);
};

/**
 * 获取配置详情
 */
export const getConfigDetail = async (id: number): Promise<ProductConfig> => {
  const product = await getProductDetail(id);
  return transformProductToConfig(product);
}; 

/**
 * 为产品添加配置
 */
export const addProductConfig = async (data: ProductConfigData): Promise<ApiResponse<any>> => {
  const response = await http.post(`/admin/products/${data.product_id}/config`, {
    config_data: data.config_data,
    config_name: data.config_name,
    config_description: data.config_description,
  });
  return response.data;
};

/**
 * 更新产品配置
 */
export const updateProductConfig = async (productId: number, data: UpdateProductConfigRequest): Promise<ApiResponse<any>> => {
  const response = await http.put(`/admin/products/${productId}/config`, data);
  return response.data;
};

/**
 * 获取产品配置
 */
export const getProductConfig = async (productId: number): Promise<ApiResponse<ProductConfigData>> => {
  const response = await http.get(`/admin/products/${productId}/config`);
  return response.data;
};

/**
 * 删除产品配置
 */
export const deleteProductConfig = async (productId: number): Promise<ApiResponse<any>> => {
  const response = await http.delete(`/admin/products/${productId}/config`);
  return response.data;
}; 

/**
 * 上传商品图片（普通图片，位置0-3）
 */
export const uploadProductImages = async (productId: number, files: File[]): Promise<ApiResponse<{ images: string[] }>> => {
  const formData = new FormData();
  
  // 添加产品ID
  formData.append('productId', productId.toString());
  formData.append('imageType', 'normal'); // 标识为普通图片
  
  // 添加图片文件
  files.forEach((file, index) => {
    formData.append('images', file);
  });

  const response = await http.post('/upload/product-images', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
  return response.data;
};

/**
 * 上传商品详情图（位置4）
 */
export const uploadProductDetailImage = async (productId: number, file: File): Promise<ApiResponse<{ images: string[] }>> => {
  const formData = new FormData();
  
  formData.append('productId', productId.toString());
  formData.append('imageType', 'detail'); // 标识为详情图
  formData.append('images', file);

  const response = await http.post('/upload/product-images', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
  
  return response.data;
};

/**
 * 删除商品图片
 */
export const deleteProductImage = async (productId: number, imageIndex: number): Promise<ApiResponse<{ images: string[] }>> => {
  const response = await http.delete(`/upload/product-images/${productId}/${imageIndex}`);
  return response.data;
};

// 产品特性相关类型
export interface ProductFeature {
  id: number;
  title: string;
  description?: string;
  icon?: string;
  highlight?: boolean;
  order: number;
}

export interface CreateFeatureRequest {
  title: string;
  description?: string;
  icon?: string;
  highlight?: boolean;
}

export interface UpdateFeaturesRequest {
  features: ProductFeature[];
}

/**
 * 获取产品特性
 */
export const getProductFeatures = async (id: number): Promise<ApiResponse<{ id: number; name: string; features: ProductFeature[] }>> => {
  const response = await http.get(`/admin/products/${id}/features`);
  return response.data;
};

/**
 * 更新产品特性
 */
export const updateProductFeatures = async (id: number, features: ProductFeature[]): Promise<ApiResponse<{ id: number; features: ProductFeature[] }>> => {
  const response = await http.put(`/admin/products/${id}/features`, { features });
  return response.data;
};

/**
 * 添加产品特性
 */
export const addProductFeature = async (id: number, feature: CreateFeatureRequest): Promise<ApiResponse<{ id: number; feature: ProductFeature; features: ProductFeature[] }>> => {
  const response = await http.post(`/admin/products/${id}/features`, feature);
  return response.data;
};

/**
 * 删除产品特性
 */
export const deleteProductFeature = async (id: number, featureId: number): Promise<ApiResponse<{ id: number; featureId: number; features: ProductFeature[] }>> => {
  const response = await http.delete(`/admin/products/${id}/features/${featureId}`);
  return response.data;
};

/**
 * 重置产品特性为默认配置
 */
export const resetProductFeatures = async (id: number): Promise<ApiResponse<{ id: number; features: ProductFeature[] }>> => {
  const response = await http.post(`/admin/products/${id}/features/reset`, {});
  return response.data;
};

 